package ysf.com.difficulty;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 三十
 * 搞不懂呀,他妈的
 * @author ysf
 * @date 2021/8/19 11:03
 */
public class ThirtyDemo {


    public static void main(String[] args) {
        String s = "barfoothefoobarman";
        String s2 ="wordgoodbestwordgoodwordbest";
        String s3 ="foofoohebarfoofoo";
        String[] words = new String[]{"foo", "bar"};
        String[] words2 = new String[]{"word", "good","best","word"};
        String[] words3 = new String[]{"foo", "foo"};
        List<Integer> index = findSubString(s2, words2);
        System.out.println(index);

    }

    public static List<Integer> findSubString(String s, String[] words) {

        List<Integer> res = new ArrayList<Integer>();
        int wordNum = words.length;
        if (wordNum == 0) {
            return res;
        }
        int wordLen = words[0].length();
        //HashMap1 存所有单词
        HashMap<String, Integer> allWords = new HashMap<String, Integer>();
        for (String w : words) {
            int value = allWords.getOrDefault(w, 0);
            allWords.put(w, value + 1);
        }
        //遍历所有⼦串
        for (int i = 0; i < s.length() - wordNum * wordLen + 1; i++) {
            //HashMap2 存当前扫描的字符串含有的单词
            HashMap<String, Integer> hasWords = new HashMap<String, Integer>();
            int num = 0;
            //判断该⼦串是否符合
            while (num < wordNum) {
                String word = s.substring(i + num * wordLen, i + (num + 1) * wordLen);
                //判断该单词在 HashMap1 中
                if (allWords.containsKey(word)) {
                    int value = hasWords.getOrDefault(word, 0);
                    hasWords.put(word, value + 1);
                    //判断当前单词的 value 和 HashMap1 中该单词的 value
                    if (hasWords.get(word) > allWords.get(word)) {
                        break;
                    }
                } else {
                    break;
                }
                num++;
            }
            //判断是不是所有的单词都符合条件
            if (num == wordNum) {
                res.add(i);
            }
        }
        return res;
    }


}
